<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;
use think\Db;
use custom\ConfigStatus as CS;
use think\Exception;
use custom\Data;
use app\common\model\User;
use DateTime;
use fast\Pinyin;

class Pet extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';
    private $fields = 'id,name,mobile,community_id,village_id,address,village_name,is_use';

    public function _initialize()
    {
        parent::_initialize();

    }


    public function putInit(){
        $lookPrice=config('site.careTotal');
        $serviceList=config('site.serviceList');
        $levelNotice=config('site.levelNotice');
        $levelList=config('site.levelList');

        $where = [];
        $where['user_id'] = $this->auth->id;

        $list = Data::name('user_address')->where($where)->field($this->fields)->lists(['with' => 'community,village']);
        $address=$list?$list['list'][0]:[];


        if($address){
            $community=$address->community;
            $contactInfo = [
                'community_id'=>$address->community_id,
                'name' => $address->name,
                'mobile' => $address->mobile,
                'address' => $address->community->province . $address->community->city . $address->community->region . $address->community->town . $address->community->name . $address->address
            ];
        }else{
            $contactInfo=[];
        }

        $all=$alllevelList=[];
        foreach ($serviceList as $k=>$v){
            $data=['name'=>$k,'price'=>intval($v),'checked'=>false];
            $all[]=$data;
        }
        $id=1;
        foreach ($levelList as $k=>$v){
            $data=['id'=>$id,'name'=>$k,'desc'=>'服务','price'=>intval($v)];
            $alllevelList[]=$data;
            $id++;
        }


        $this->success('成功',[
                'careTotal'=>intval($lookPrice),
                'serviceList'=>$all,
                'levelNotice'=>$levelNotice,
                'levelList'=>$alllevelList,
                'addr'=>$contactInfo

            ]
        );
    }

    public function addFosterOrder(){
        $params = $this->request->post();
        $order_no = 'PO' . date('YmdHis') . mt_rand(1000, 9999);
        $insert=[
            'order_no' =>$order_no,
            'user_id' =>$this->auth->id,
            'levels' =>$params['starLevels'],
            'pet_ids' =>$params['petIds'],
            'remark' =>$params['remark'],
            'start_date'    => $this->formatDate($params['start_date']),
            'end_date'      => $this->formatDate($params['end_date']),
            'createtime'=>time(),
            'total_money'=>$params['totalPrice'],
            'low_money' =>$params['minEstimate'],
            'high_money' =>$params['maxEstimate'],
            'total_hours' =>$params['totalHours'],
            'community_id'=>$params['community_id'],
            'mobile'=>$params['mobile'],
            'contact'=>$params['contact'],
        ];
        Db::name('petorder')->insert($insert);



        $jiyangshiids=Db::name('jiyangshi_community')
            ->where(['community_id'=>$params['community_id']])
            ->where('status','1')
            ->column('jiyangshi_id');

        $starLevels=explode(',',$params['starLevels']);


        if($jiyangshiids){
            $userids=Db::name('jiyangshi_applyfor')
                ->where('id','in',$jiyangshiids)
                ->where('level','in',$starLevels)
                ->column('user_id');

            foreach ($userids as $k=>$v){
                setMsg($v, '订单大厅来新单了');
            }
        }


        $this->success('成功');
    }


    public function addCareOrder(){
        $params = $this->request->post();
        $order_no = 'PO' . date('YmdHis') . mt_rand(1000, 9999);


        $levelList=config('site.levelList');
        $key=array_keys($levelList);

        $insert=[
            'order_no' =>$order_no,
            'user_id' =>$this->auth->id,
            'levels' =>$params['starLevels'],
            'pet_ids' =>$params['petIds'],
            'remark' =>$params['remark'],
            'care_date'=>$this->formatDate($params['care_date']),
            'address'=>$params['address'],
            'type' =>2,
            'createtime'=>time(),
            'total_money'=>$params['totalPrice'],
            'community_id'=>$params['community_id'],
            'mobile'=>$params['mobile'],
            'contact'=>$params['contact'],
            'levels'=>implode(',',$key),

        ];
        Db::name('petorder')->insert($insert);


        $jiyangshiids=Db::name('jiyangshi_community')
            ->where(['community_id'=>$params['community_id']])
            ->where('status','1')
            ->column('jiyangshi_id');




        if($jiyangshiids){
            $userids=Db::name('jiyangshi_applyfor')
                ->where('id','in',$jiyangshiids)

                ->column('user_id');

            foreach ($userids as $k=>$v){
                setMsg($v, '订单大厅来新单了');
            }
        }

        $this->success('成功');
    }


    protected function formatDate($str)
    {
        if (preg_match('/(\\d+)月(\\d+)日\\s*(\\d+)点/', $str, $m)) {
            $year = date('Y');
            $month = str_pad($m[1], 2, '0', STR_PAD_LEFT);
            $day = str_pad($m[2], 2, '0', STR_PAD_LEFT);
            $hour = str_pad($m[3], 2, '0', STR_PAD_LEFT);
            return "{$year}-{$month}-{$day} {$hour}:00:00";
        }
        return date('Y-m-d H:i:s');
    }
    public function addPet()
    {

        $params = $this->request->post();

        // 参数验证，可根据需求扩展
        $rule = [

            'name'   => 'require',
            'breed'  => 'require',
            'gender' => 'require',
            'birth'  => 'require',
        ];

        $msg = [

            'name.require'   => '宠物姓名不能为空',
            'breed.require'  => '宠物品种不能为空',
            'gender.require' => '宠物性别不能为空',
            'birth.require'  => '宠物生日不能为空',
        ];

        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }

        // 写入数据库
        $result = Db::name('pet')->insert([
            'avatar' => $params['avatar'],
            'name'   => $params['name'],
            'breed'  => $params['breed'],
            'gender' => $params['gender'],
            'birth'  => $params['birth'],
            'is_jueyu'  => $params['is_jueyu'],
            'is_yimiao'  => $params['is_yimiao'],
            'createtime'=>time(),
            'user_id'=>$this->auth->id,
            'remark' => isset($params['remark']) ? $params['remark'] : '',

        ]);

        if ($result) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }

    }

    public function petList()
    {
        $list = Db::name('pet')
            ->whereNull('deletetime')
            ->where('user_id', $this->auth->id)
            ->field('id,avatar, name, birth,breed')
            ->select();

        if ($list) {
            foreach ($list as &$item) {
                if ($item['birth']) {
                    $birthDate = new DateTime($item['birth']);
                    $now = new DateTime();
                    $interval = $now->diff($birthDate);
                    $item['age'] = $interval->y;
                } else {
                    $item['age'] = 0;
                }
            }
            $this->success('获取成功', ['list'=>$list]);
        } else {
            $this->error('未找到宠物列表');
        }
    }


    public function breedList()
    {
        $dogHotList=Db::name('breed')
            ->where('type', '1')
            ->where('is_hot', '1')
            ->select();


        $catHotList = Db::name('breed')
            ->where('type', '2')
            ->where('is_hot', '1')
            ->select();

        $allDogList = Db::name('breed')
            ->where('type', '1')
            ->select();
        $allDogList=$this->getBreedListByAlpha($allDogList);
        $allCatList = Db::name('breed')
            ->where('type', '2')
            ->select();
        $allCatList=$this->getBreedListByAlpha($allCatList);

        $return =[
            'dog_hot_list' => $dogHotList,
            'cat_hot_list' => $catHotList,
            'all_dog_list' => $allDogList,
            'all_cat_list' => $allCatList,
        ];
        $this->success('获取成功', $return);
    }

    public function getBreedListByAlpha($breeds)
    {

        $alphaList = [];
        foreach ($breeds as $breed) {
            $firstChar = $breed['letter'];

            if (!isset($alphaList[$firstChar])) {
                $alphaList[$firstChar] = ['letter' => $firstChar, 'breeds' => []];
            }

            $alphaList[$firstChar]['breeds'][] = $breed;
        }
        ksort($alphaList);
        return array_values($alphaList);
    }


    public function petDetail()
    {
        $post = $this->request->post();
        $pet_id=$post['id'];
        $pet=Db::name('pet')
            ->where('id', $pet_id)
            ->where('user_id', $this->auth->id)
            ->find();
        if(!$pet){
            $this->error('未找到宠物');
        }

        $pet['tags']=explode(',',$pet['tags']);
        $this->success('获取成功', $pet);

    }

    public function refuse()
    {
        $id = $this->request->post('id');
        Db::name('petorder')->where('id',$id)->update(['accepttime'=>null,'jiyangshi_id'=>0,'status'=>0]);
        $this->success('成功');
    }

    public function editPet()
    {
        $params = $this->request->post();
        // 参数验证，可根据需求扩展
        $rule = [
            'name'   => 'require',
            'breed'  => 'require',
            'gender' => 'require',
            'birth'  => 'require',
        ];
        $msg = [
            'name.require'   => '宠物姓名不能为空',
            'breed.require'  => '宠物品种不能为空',
            'gender.require' => '宠物性别不能为空',
            'birth.require'  => '宠物生日不能为空',
        ];

        $validate = new \think\Validate($rule, $msg);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }



        // 写入数据库
        $result = Db::name('pet')->where('id',$params['id'])->update([
            'avatar' => $params['avatar'],
            'name'   => $params['name'],
            'breed'  => $params['breed'],
            'gender' => $params['gender'],
            'birth'  => $params['birth'],
            'updatetime'=>time(),
            'remark' => isset($params['remark']) ? $params['remark'] : '',
            'is_jueyu'  => $params['is_jueyu'],
            'is_yimiao'  => $params['is_yimiao'],
        ]);

        if ($result) {
            $this->success('添加成功');
        } else {
            $this->error('添加失败');
        }

    }

    public function mingpian(){

        $post = $this->request->post();
        $id=$post['id'];




        $res=db('jiyangshi_applyfor')->where('id', $id)->find();





        $jy_type_str = $res['servicetypes'];
        $jy_type_arr = $jy_type_str ? explode(',', $jy_type_str) : []; // 转为数组





        $res['servicetypes']=$jy_type_arr;
        $res['images']=explode(',',$res['images']);
        $res['avatar']=$res['avatar']?$res['avatar']:'';

        $this->success('成功',$res);
    }


    public function petInfo()
    {
        $info = Db::name('pet')
            ->whereNull('deletetime')
            ->where('user_id', $this->auth->id)
            ->order('id desc')
            ->find();

        if($info){

            $birthDate = new DateTime($info['birth']);
            $now = new DateTime();
            $interval = $now->diff($birthDate);
            $info['age'] = $interval->y;
        }

        $this->success('获取成功', ['info'=>$info]);
    }

    public function petDelete()
    {
        $post = $this->request->post();
        $pet_id=$post['id'];
        Db::name('pet')
            ->where('id', $pet_id)
            ->update(['deletetime'=>time()]);


        $this->success('删除成功');
    }
    public function order()
    {

        $post = $this->request->post();
        // 获取参数
        $type = $this->request->post('type');      // 订单类型
        $status = $this->request->post('status');  // 状态
        $keyword = $this->request->post('keyword');
        $page = $this->request->post('page',1);
        $size = $this->request->post('size',10);
        $list = [];
        $where = [];

        // 获取骑手身份
        $userId = $this->auth->id;

        $where['user_id'] = $userId;
        if($status!=-1){
            $where['status'] = $status;
        }

        if($status==0){
            $where['status'] = 0;
        }
        // if($status==5){
        //     $where['status'] = '0';
        //     $where['is_yuyue'] = 1;
        //     $where['yuyue_status'] = '0';
        //     $where['is_pay'] = '1';
        // }
        $list = Db::name('petorder')
            ->order('id desc')
            ->where($where)
            ->field('id,type,total_money,pet_ids,start_date,end_date,care_date,createtime,is_pay,order_no,status,jiyangshi_id')
            ->page($page,$size)
            ->select();
        // 获取每个订单的宠物信息
        foreach($list as $k=>$order) {
            if(!empty($order['pet_ids'])) {
                $petIds = explode(',', $order['pet_ids']);
                $list[$k]['pets'] = Db::name('pet')
                    ->where('id', 'in', $petIds)
                    ->select();
            } else {
                $list[$k]['pets'] = [];
            }
            $list[$k]['createtime']= date('Y-m-d H:i:s',$order['createtime']);
            $list[$k]['start_date']=$this->reverseFormatDate($order['start_date']);
            $list[$k]['end_date']=$this->reverseFormatDate($order['end_date']);
            switch ($order['status']) {
                case '0':
                    $list[$k]['status_text'] = '待接单';
                    break;
                case '1':
                    $list[$k]['status_text'] = '待支付';
                    break;
                case '2':
                    $list[$k]['status_text'] = '待结单';
                    break;
                case '3':
                    $list[$k]['status_text'] = '待确认';
                    break;
                case '4':
                    $list[$k]['status_text'] = '已完成';
                    break;
                case '8':
                    $list[$k]['status_text'] = '已取消';
                    break;
                default:
                    break;
            }
        }
        $total=Db::name('petorder')->where($where)->count();
        $this->success('获取成功', ['list'=>$list,'total'=>$total]);

    }

    public function confirm(){
        $id = $this->request->post('id');  // 状态
        $order = Db::name('petorder')->where('id', $id)->find();
        if ($order['status']!=3 ){
            $this->error('该订单状态有误');
        }else{
            Db::name('petorder')->where('id', $id)->update(['status'=>4,'confirmtime'=>time()]);
            $user_id=Db::name('jiyangshi_applyfor')->where('id',$order['jiyangshi_id'])->value('user_id');

            setMsg($user_id, '订单'.$order['order_no'].'客户已确认');

            $user=new User();
            $user->money($order['total_money'],$user_id,'订单号202506032027567513',['cate'=>1,'order_id'=>$id]);


            $jifen=ceil($order['pay_money']*config('site.percent'));
            $user->score($jifen,$user_id,'订单号202506032027567513',['order_id'=>$id]);
            $this->success('成功');
        }
    }

    public function cancel(){
        $id = $this->request->post('id');  // 状态
        $order = Db::name('petorder')->where('id', $id)->find();
        if ($order['status']!='0') {
            $this->error('该订单已接单');
        }else{
            Db::name('petorder')->where('id', $id)->update(['status'=>'8','canceltime'=>time()]);

            if($order['coupon_id']){
                Db::name('user_coupon')->where('coupon_id',$order['coupon_id'])->where('user_id',$this->auth->id)->update(['status'=>0]);
            }
            $this->success('成功');
        }
    }

    protected function reverseFormatDate($datetime)
    {
        if (empty($datetime)) {
            return '';
        }

        $timestamp = strtotime($datetime);
        if ($timestamp === false) {
            return $datetime;
        }

        $month = date('n', $timestamp); // 无前导零的月份
        $day = date('j', $timestamp);   // 无前导零的日期
        $hour = date('G', $timestamp);  // 24小时制，无前导零

        return "{$month}月{$day}日 {$hour}点";
    }

    public function pay()
    {
        $params = $this->request->post();

        $order_id = $params['id'];

        $data=Db::name('petorder')->where('id', $order_id)->find();


        if($data['is_pay']==1){
            $this->error('订单已支付');
        }

        $openid=User::where('id',$this->auth->id)->value('openid');

        if ($order_id) {

            $type='wechat';
            $notifyurl = config('other.WEB_DOMAIN_NAME').'/api/jiyangshi/jynotify';

            $returnurl = config('other.WEB_DOMAIN_NAME').'/returnx/'.$type;
            $params = [
                'amount'=>"0.01",
                'orderid'=>$data['order_no'],
                'type'=>"wechat",
                'title'=>"订单标题",
                'notifyurl'=>$notifyurl,
                'returnurl'=>$returnurl,
                'method'=>"miniapp",
                'openid'=>"$openid",
            ];

            $response = \addons\epay\library\Service::submitOrder($params);
            $this->success('成功',['order_id' => $order_id, 'order_no' => $data['order_no'],'pay_params'=>$response]);
        } else {
            $this->error('支付失败');
        }
    }




    public function jyinfoList()
    {
        $id = $this->request->post('id');
        $list=Db::name('jyinfo')->where('order_id',$id)->order('id desc')->select();
        foreach ($list as $k => $v) {

            $list[$k]['images'] = explode(',', $v['images']);
            $list[$k]['videos'] = explode(',', $v['videos']);
        }
        $this->success('成功',['list'=>$list]);
    }



    public function jyorderinfo()
    {
        $id = $this->request->post('id');
        $list=Db::name('jyinfo')->where('order_id',$id)->select();
        foreach ($list as $k => $v) {
            $list['createtime']=date('Y-m-d H:i:s', $v['createtime']);
        }
        $this->success('成功',['list'=>$list]);
    }




}
